package com.cy.aircompressor.main.ui.onlinemonitor.fragment.child;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.ChildRealtimeDataFragmentBinding;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.sensor.SensorItemData;
import com.cy.aircompressor.entity.sensor.SensorProvider;
import com.cy.aircompressor.entity.warning.WarningMsg;
import com.cy.aircompressor.main.ui.onlinemonitor.fragment.OnlineMonitorFragment;
import com.cy.aircompressor.main.ui.onlinemonitor.provider.SensorItemProvider;
import com.cy.aircompressor.main.ui.onlinemonitor.provider.SingleAirWarningMsgProvider;
import com.cy.aircompressor.main.ui.onlinemonitor.viewmodel.OnlineMonitorViewModel;
import com.cy.aircompressor.main.home.other.WarningFragment;
import com.cy.aircompressor.main.view.spaceItem.GridSpaceItem2Decoration;
import com.drug.lib.util.DensityUtil;
import com.drug.lib.view.recycptr.DynamicAdpTypePool;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.bean.RowEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMFragment;
import com.net.model.livedatas.LiveDataBus;
import com.net.model.utils.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class RealTimeDataFragment extends BaseVMFragment<ChildRealtimeDataFragmentBinding, OnlineMonitorViewModel> {

    public static RealTimeDataFragment newInstance() {
        Bundle args = new Bundle();
        RealTimeDataFragment fragment = new RealTimeDataFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void dataChange() {
        mViewModel.getQueryWarningByPageObservable().observe(this, new Observer<Resource<RowEntity<WarningMsg>>>() {
            @Override
            public void onChanged(Resource<RowEntity<WarningMsg>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<WarningMsg>>() {
                    @Override
                    public void onSuccess(RowEntity<WarningMsg> data) {
                        warningMsgAdapter.setItems(data.getList());
                        warningMsgAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Integer code, String message) {
                        super.onFailure(code, message);
                        if (code == Constant.EMPTY_DATA_ERROR) {
                            warningMsgAdapter.setItems(new ArrayList<>());
                            warningMsgAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        });

        mViewModel.getQueryCompressorSensorDataObservable().observe(this, new Observer<Resource<List<SensorLatestData>>>() {
            @Override
            public void onChanged(Resource<List<SensorLatestData>> listResource) {
                listResource.handler(new OnCallback<List<SensorLatestData>>() {
                    @Override
                    public void onSuccess(List<SensorLatestData> data) {
                        if (data == null || data.size() == 0) {
                            clearItemData();
                        } else {
                            List<SensorLatestData> sensorLatestDataList = null;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                sensorLatestDataList = data.stream()
                                        .filter(new Predicate<SensorLatestData>() {
                                            @Override
                                            public boolean test(SensorLatestData sensorLatestData1) {
                                                return TextUtils.equals(sensorLatestData1.getCompressorId(), OnlineMonitorFragment.selectDict.getValue());
                                            }
                                        }).collect(Collectors.toList());
                            }

                            List<SensorItemData> dataList = null;
                            if (sensorLatestDataList != null && sensorLatestDataList.size() != 0) {
                                dataList = sensorLatestDataList.get(0).getDataList();
                            }
                            if (dataList != null) {
                                List<SensorProvider> sensorProviders = sensorAdapter.getItems();
                                for (SensorProvider sensorProvider : sensorProviders) {
                                    filterSensor(dataList, sensorProvider);
                                }
                            } else {
                                clearItemData();
                            }
                            sensorAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(Integer code, String message) {
                        super.onFailure(code, message);
                        if (code == Constant.EMPTY_DATA_ERROR) {
                            clearItemData();
                        }
                    }
                });
            }
        });

        LiveDataBus.get(RealTimeDataFragment.class.getSimpleName(), SelectDict.class).observe(this, new Observer<SelectDict>() {
            @Override
            public void onChanged(SelectDict selectDict) {
                requestNetwork();
            }

        });
    }

    private void clearItemData() {
        List<SensorProvider> sensorProviders = sensorAdapter.getItems();
        for (SensorProvider sensorProvider : sensorProviders) {
            sensorProvider.setTemperatureItemData(null);
            sensorProvider.setPressureItemData(null);
            sensorProvider.setOilItemData(null);
            sensorProvider.setWaterItemData(null);
            sensorProvider.setVibration1ItemData(null);
            sensorProvider.setVibration2ItemData(null);
            sensorProvider.setVibration3ItemData(null);
        }
        sensorAdapter.notifyDataSetChanged();
    }

    private void filterSensor(List<SensorItemData> dataList, SensorProvider sensorProvider) {
        List<SensorItemData> result = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            result = dataList.stream()
                    .filter(new Predicate<SensorItemData>() {
                        @Override
                        public boolean test(SensorItemData sensorItemData) {
                            return TextUtils.equals(sensorItemData.getCompressorPartCode(), sensorProvider.getSelectDict().getValue());
                        }
                    }).collect(Collectors.toList());
        }

        for (SensorItemData sensorItemData : result) {
            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "pressure")) {
                sensorProvider.setPressureItemData(sensorItemData);
            }
            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "temperature")) {
                sensorProvider.setTemperatureItemData(sensorItemData);
            }


            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "vibration1")) {
                sensorProvider.setVibration1ItemData(sensorItemData);
            }
            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "vibration2")) {
                sensorProvider.setVibration2ItemData(sensorItemData);
            }
            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "vibration3")) {
                sensorProvider.setVibration3ItemData(sensorItemData);
            }

            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "pressure_water")) {
                sensorProvider.setWaterItemData(sensorItemData);
            }
            if (TextUtils.equals(sensorItemData.getCompressorPointCode(), "pressure_oil")) {
                sensorProvider.setOilItemData(sensorItemData);
            }
        }

    }

    @Override
    protected ChildRealtimeDataFragmentBinding getViewBinding() {
        return ChildRealtimeDataFragmentBinding.inflate(getLayoutInflater());
    }


    @Override
    protected void initData() {
        initSensorDataRecycler();
        initWarningMsgRecycler();
        RxView.clicks(mBinding.btnMore)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    WarningFragment.showDialogFragment(getChildFragmentManager(), "3", OnlineMonitorFragment.selectDict.getValue());
                });
    }

    @Override
    protected void requestNetwork() {
        mViewModel.queryWarningByPage(OnlineMonitorFragment.selectDict.getValue());
        initParts();
        queryCompressorSensor();
    }


    private void queryCompressorSensor() {
        List<String> list = new ArrayList<>();
        list.add(OnlineMonitorFragment.selectDict.getValue());
        mViewModel.queryCompressorSensorData(list);
    }

    DynamicRecyclerAdapter sensorAdapter;

    private void initSensorDataRecycler() {
        GridLayoutManager mLayoutManager = new GridLayoutManager(mContext, 2);
        // 添加间距
        mBinding.recyclerView.addItemDecoration(new GridSpaceItem2Decoration(2,
                DensityUtil.dip2px(10),
                DensityUtil.dip2px(10)));
        mBinding.recyclerView.setLayoutManager(mLayoutManager);
        sensorAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        SensorItemProvider sensorItemProvider = new SensorItemProvider(mContext);
        pool.register(SensorProvider.class, sensorItemProvider);
        sensorAdapter.registerAll(pool);
        mBinding.recyclerView.setAdapter(sensorAdapter);
    }

    private void initParts() {
        List<SelectDict> compressorParts = AirConfig.get().compressorParts;
        if (compressorParts == null) return;
        if (sensorAdapter == null) return;
        if (sensorAdapter.getItems().size() != 0) return;
        List<SensorProvider> sensorProviders = new ArrayList<>();
        for (SelectDict selectDict : compressorParts) {
            SensorProvider sensorProvider = new SensorProvider();
            sensorProvider.setSelectDict(selectDict);
            sensorProviders.add(sensorProvider);
        }
        sensorAdapter.setItems(sensorProviders);
        sensorAdapter.notifyDataSetChanged();
    }

    DynamicRecyclerAdapter warningMsgAdapter;

    private void initWarningMsgRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.warningView.setLayoutManager(mLayoutManager);
        warningMsgAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        SingleAirWarningMsgProvider singleAirWarningMsgProvider = new SingleAirWarningMsgProvider();
        pool.register(WarningMsg.class, singleAirWarningMsgProvider);
        warningMsgAdapter.registerAll(pool);
        mBinding.warningView.setAdapter(warningMsgAdapter);
    }
}
